package com.yantu.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    RedisUtils redisUtils;

    /**
     * redis存入数据
     * @param key 键名
     * @param value  值
     * */
    public boolean saveValue(String key, Object value){
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }

    public boolean saveValueTime(String key, Object value,int time){
        try {
            if (time>0){
                redisTemplate.opsForValue().set(key, value,time,TimeUnit.DAYS);
                return true;
            }else {
                redisTemplate.opsForValue().set(key, value);
                return true;
            }

        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }

    /**
     * 获取redis中的值
     * @param key 键名
     * */
    public  Object getValue(String key){
        if(key==null){
            return null;
        }else {
            return redisTemplate.opsForValue().get(key);
        }
    }
    /**
     * 删除redis中的所有缓存
     * @param
     * */
    public  void delAll(){
        Set keys = redisTemplate.keys("*");
        if (ObjectUtils.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除redis中的值
     * @param keys 键名
     * */
    public boolean delkey(String... keys){
        if(keys!=null &&keys.length>0){
            if(keys.length==1){
                redisTemplate.delete(keys[0]);
                return true;
            }else {
                for (String key : keys){
                    redisTemplate.delete(key);
                }
                return true;
            }
        }else {
            return false;
        }
    }
    /**
     * 判断key是否存在
     * @param key 键名
     * */
    public boolean haskeysf(String key){
        try{
            System.out.println(redisTemplate.hasKey(key));
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            System.out.println("redis值不存在");
            System.out.println(e.getMessage());
            return false;
        }
    }

    /**
     * 获取redis的过期时间
     * 0代表永久有效
     * 大于0就剩多少分钟才失效
     * @param key 键名
     * @return*/
    public Long keyisExpired(String key){
        return redisTemplate.getExpire(key,TimeUnit.DAYS);
    }
}
